package com.example.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.domain.User;
import com.example.result.UserResult;
import com.example.service.IUserService;
import com.example.untils.MailUntils;
import com.example.untils.RedisConstants;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private StringRedisTemplate template;
    //用户名密码登录
    @PostMapping("/login")
    public UserResult login(@RequestBody User user){
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        wrapper.eq("password",user.getPassword());
        User res = iUserService.getOne(wrapper);
        UserResult userResult = new UserResult(res);
        //两用户信息转为map
        Map<String, Object> map = BeanUtil.beanToMap(userResult);

        template.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY,map);
        //设置存活时间
        template.expire(RedisConstants.LOGIN_USER_KEY,RedisConstants.LOGIN_USER_TTL,TimeUnit.HOURS);
        return userResult;
    }
    //获取用户信息
    @GetMapping("/gainUser")
    public UserResult gainUser(){
        //从redis中获取用户信息
        Map<Object, Object> map = template.opsForHash().entries(RedisConstants.LOGIN_USER_KEY);
        //map转化为对象
        User res = BeanUtil.fillBeanWithMap(map, new User(), false);
        UserResult userResult = new UserResult(res);
        //重置时间
        template.expire(RedisConstants.LOGIN_USER_KEY,RedisConstants.LOGIN_USER_TTL, TimeUnit.HOURS);
        return userResult;
    }
    //注销
    @GetMapping("/logout")
    public ModelAndView logout(ModelAndView modelAndView){
        template.delete(RedisConstants.LOGIN_USER_KEY);
        ModelAndView view = new ModelAndView("redirect:/login.html");
        return view;
    }
    //获取验证码
    @GetMapping("/gainVerCode/{email}")
    public Boolean gainVerCode(@PathVariable String email){
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("email",email);
        User user = iUserService.getOne(wrapper);
        if(user==null){
            return false;
        }else{
            String sb = RandomUtil.randomString(4);
            javaMailSender.send(MailUntils.sendMail(user.getEmail(),sb));
            template.opsForValue().set(RedisConstants.LOGIN_CODE_KEY +user.getEmail(),sb,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
            return true;
        }
    }
    //邮箱登录
    @GetMapping("/loginEmail/{verCode}/{email}")
    public Boolean loginEmail(HttpSession session,@PathVariable String verCode,@PathVariable String email){
        String sb=(String)template.opsForValue().get(RedisConstants.LOGIN_CODE_KEY+email);

        if(verCode.equalsIgnoreCase(sb)){
            QueryWrapper<User> wrapper=new QueryWrapper<>();
            wrapper.eq("email",email);
            User res = iUserService.getOne(wrapper);
            UserResult userResult = new UserResult(res);
            //两用户信息转为map
            Map<String, Object> map = BeanUtil.beanToMap(userResult);

            template.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY,map);
            //设置存活时间
            template.expire(RedisConstants.LOGIN_USER_KEY,RedisConstants.LOGIN_USER_TTL,TimeUnit.HOURS);
            return true;
        }else{
            return false;
        }
    }
    //注册信息
    @PostMapping("/register")
    public Boolean register(@RequestBody User user){
        System.out.println(user);
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        wrapper.or().eq("email",user.getEmail());
        User temp = iUserService.getOne(wrapper);
        if(temp!=null){
            return false;
        }else{
            iUserService.save(user);
            return true;
        }
    }
}
